import request from '../../utils/request'
import {
  getCount
} from '../../utils/getCart_id'
Page({
  data: {
    cartList: "",
    count: "",
    isAll: false,
    totalPrice: '',
    allNum:'',
    isLogin:false
  },
  onLoad: function () {
    this.dataInit()
  },
  onShow: function () {
    this.dataInit()
    let userInfo=wx.getStorageSync('userInfo')
    if(userInfo){
      this.setData({
        isLogin:true
      })
    }
  },
  // 点击按钮
  select(e) {
    let index = e.currentTarget.dataset.index
    let temArr = this.data.cartList
    temArr[index].isCheck = !this.data.cartList[index].isCheck
    this.setData({
      cartList: temArr
    })
    let selectCart = wx.getStorageSync('selectCart')
    if (selectCart) {
      let isFlag = false
      selectCart.forEach(item => {
        if (!isFlag) {
          if (item.good_id == temArr[index].good_id && JSON.stringify(item.sku) == JSON.stringify(temArr[index].sku)) {
            item.state = this.data.cartList[index].isCheck
            isFlag = true
          }
        }
      })
      if (!isFlag) {
        selectCart.push({
          good_id: temArr[index].good_id,
          state: temArr[index].isCheck,
          sku: temArr[index].sku
        })
      }
      wx.setStorageSync('selectCart', selectCart)
    } else {
      wx.setStorageSync('selectCart', [{
        good_id: temArr[index].good_id,
        state: temArr[index].isCheck,
        sku: temArr[index].sku
      }])
    }
    this.Allmoney()
    this.whetherCheck()
    this.settlementAmount()
  },
  addNum(e) {
    let index = e.currentTarget.dataset.index
    let temArr = this.data.cartList
    temArr[index].num++
    temArr[index].money = (temArr[index].num * (temArr[index].price * 1)).toFixed(2)
    this.modifyCart(temArr[index])
    this.setData({
      cartList: temArr
    })
    this.settlementAmount()
  },
  downNum(e) {
    let index = e.currentTarget.dataset.index
    let temArr = this.data.cartList
    if (temArr[index].num > 1) {
      temArr[index].num--
      temArr[index].money = (temArr[index].num * (temArr[index].price * 1)).toFixed(2)
      this.modifyCart(temArr[index])
      this.setData({
        cartList: temArr
      })
    } else {
      wx.showToast({
        title: '最少购买一件',
        icon: 'none'
      })
    }
    this.settlementAmount()
  },
  // 修改购物车
  async modifyCart(Arr) {
    let token = wx.getStorageSync("userInfo").token
    let res = await request("/api/shoppingCarAddModify", {
      token,
      ...Arr
    })
    this.Allmoney()
  },
  // 购物车的勾选
  judgeCheck(Arr) {
    let selectArr = wx.getStorageSync('selectCart')
    if (selectArr) {
      Arr.forEach(item => {
        let flag = false
        selectArr.forEach(itemm => {
          if (!flag) {
            if (item.good_id == itemm.good_id && JSON.stringify(item.sku) == JSON.stringify(itemm.sku) && itemm.state == true) {
              item.isCheck = true
              flag = true
            } else {
              item.isCheck = false
            }
          }
        })
      })
    }
    return Arr
  },
  toDetail(e) {
    let good_id = e.currentTarget.dataset.goodid;
    wx.navigateTo({
      url: `../details/details?good_id=${good_id}`,
    })
  },
  async dataInit() {
    let userInfo=wx.getStorageSync('userInfo')
    if(userInfo){
      let size = await getCount()
      let token = wx.getStorageSync("userInfo").token
      let res = await request("api/shoppingCarList", {
        token,
        size
      })
      if (res.code === 2000) {
        let cartList = this.judgeCheck(res.data.data)
        console.log(cartList);
        this.setData({
          cartList: cartList.reverse(),
          count: res.data.count
        })
        this.Allmoney()
      }
      this.whetherCheck()
      this.settlementAmount()
    }
  },
  // 全选
  selectAll() {
    this.setData({
      isAll: !this.data.isAll
    })
    let temArr = this.data.cartList
    if (this.data.isAll) {
      temArr.forEach(item => {
        item.isCheck = true
      })
      this.setData({
        cartList: temArr
      })
      this.cartCheck()
  
    } else {
      temArr.forEach(item => {
        item.isCheck = false
      })
      this.setData({
        cartList: temArr
      })
      wx.removeStorageSync('selectCart')
    }
    this.Allmoney()
    this.settlementAmount()
  },
  // 计算合计
  Allmoney() {
    let allMoney = 0
    this.data.cartList.forEach(item => {
      if (item.isCheck) {
        allMoney += Number(item.money)
      }
    })
    allMoney = allMoney.toFixed(2)
    this.setData({
      totalPrice: allMoney
    })
  },
  // 全选
  cartCheck() {
    wx.removeStorageSync('selectCart')
    let selectCart=[]
    let tem = this.data.cartList
    tem.forEach(item=>{
      selectCart.push({good_id:item.good_id,state:true,sku:item.sku})
    })
    wx.setStorageSync('selectCart', selectCart)
  },
  // 判断是否全选
  whetherCheck(){
      let check=this.data.cartList.every(item=>{
        return item.isCheck==true
      })
      if(this.data.cartList.length<1){
        check=false
      }
     this.setData({
      isAll:check
     })
  },
  // 删除购物车
  async deleteCart(e){
    let token=wx.getStorageSync('userInfo').token
    let shopping_car_id=e.currentTarget.dataset.cartid;
   let res=await request("api/shoppingCarDelete",{
      shopping_car_id,
      token
    })
    console.log(res);
    if(res.code===2000){
      this.dataInit()
    }
  },
  // 判断结算的金额
  settlementAmount(){
    let allNum=0
    let allCart=this.data.cartList
    allCart.forEach(item=>{
      if(item.isCheck){
        allNum+=Number(item.num)
      }
    })
    this.setData({
      allNum:allNum
    })
  },
  // 去结账
  toCheckOut(){
    let temArr=this.data.cartList
    let settlement=[]
    temArr.forEach(item=>{
      if(item.isCheck){
        settlement.push(item)
      }
    })
    wx.setStorageSync('settlement', settlement)
   if(settlement.length>0){
    wx.navigateTo({
      url: '../address/address',
    })
   }else{
     wx.showToast({
       title: '至少选择一样商品',
       icon:"none"
     })
   }
  },
  login(){
    wx.navigateTo({
      url: '../login/login',
    })
  }
});